package cn.fl.mcr.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.hazelcast.util.Clock;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrWriteOffConfirmSummaryService;
import cn.fl.mcr.vo.McrWriteOffConfirmSummaryDVO;
import cn.fl.system.constant.SysLogConstant;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrWriteOffConfirmSummaryQC;
import cn.lionbridgecapital.loan.model.dto.PushWriteOffInfoDTO;
import cn.lionbridgecapital.loan.model.vo.McrWriteOffConfirmSummaryVO;

/**
 * @Description: 核销确认汇总 控制层
 */
@Controller
@RequestMapping("/mcr/mcrWriteOffConfirmSummary")
public class McrWriteOffConfirmSummaryController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrWriteOffConfirmSummaryController.class);

	/**
	 * McrWriteOffConfirmSummary 服务层BEAN
	 */
	@Autowired
	private IMcrWriteOffConfirmSummaryService mcrWriteOffConfirmSummaryService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmSummary/writeOffConfirmSummarylist");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmSummary/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		McrWriteOffConfirmSummaryQC qc = new McrWriteOffConfirmSummaryQC();
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		String batNo = request.getParameter("batNo");
		if(StringUtils.isNotEmpty(batNo)) {
			qc.setBatNo(batNo);//批次号
		}
		String commitType = request.getParameter("commitType");
		if(StringUtils.isNotEmpty(commitType)) {
			qc.setCommitType(commitType);//
		}
		
		String repayAmt = request.getParameter("repayAmt");
		if(StringUtils.isNotEmpty(repayAmt)){
			qc.setRepayAmt(DecimalUtils.convertYuanToFen(Double.valueOf(repayAmt)));//实收总金额
		}
		String crtTmStart = request.getParameter("crtTmStart");//创建时间
		if(StringUtils.isNotEmpty(crtTmStart)){
			qc.setCrtTmStart(crtTmStart);
		}
		String crtTmEnd = request.getParameter("crtTmEnd");
		if(StringUtils.isNotEmpty(crtTmEnd)){
			qc.setCrtTmEnd(crtTmEnd);
		}
		String commitTmStart = request.getParameter("commitTmStart");//提交时间
		if(StringUtils.isNotEmpty(commitTmStart)){
			qc.setCommitTmStart(commitTmStart);
		}
		String commitTmEnd = request.getParameter("commitTmEnd");//提交时间
		if(StringUtils.isNotEmpty(commitTmEnd)){
			qc.setCommitTmEnd(commitTmEnd);
		}
		page.setCondition(qc);
		Pager pager = new Pager();//
		BaseLogUtils.info(logger, "McrWriteOffConfirmSummaryController->initList"+CurrentThreadContext.getCurrentUserName(), "核销确认请求参数:"+JSON.toJSONString(page));
		pager = this.mcrWriteOffConfirmSummaryService.searchListPage(page);
		List<McrWriteOffConfirmSummaryVO> list = (List<McrWriteOffConfirmSummaryVO>) pager.getResultList();
		BaseLogUtils.info(logger, "McrWriteOffConfirmSummaryController->initList", "pager转VO:"+JSON.toJSONString(list));
		ListPageVO<McrWriteOffConfirmSummaryVO> listPage = new ListPageVO<McrWriteOffConfirmSummaryVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrWriteOffConfirmSummaryService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrWriteOffConfirmSummaryVO vo = this.mcrWriteOffConfirmSummaryService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		McrWriteOffConfirmSummaryVO entity = null;
		try {
			entity = new McrWriteOffConfirmSummaryVO();
			//TODO ADD PARAM
			Long id = this.mcrWriteOffConfirmSummaryService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		McrWriteOffConfirmSummaryVO entity = null;
		try {
			entity = new McrWriteOffConfirmSummaryVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.mcrWriteOffConfirmSummaryService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	/**
	 * 
	 * @Title: confirmAndSubmitView   
	 * @Description: 确认提交页面
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ModelAndView      
	 * @throws
	 */
	@RequestMapping(value = "/confirmAndSubmitView.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView confirmAndSubmitView(HttpServletRequest request, HttpServletResponse response) {
		String batNos = request.getParameter("batNos");
		String repayAccountMoney = request.getParameter("repayAccountMoney");
		String repayAccountNum = request.getParameter("repayAccountNum");
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmSummary/writeOffConfirmAndSubmitView");
		view.addObject("batNos", batNos);
		view.addObject("repayAccountMoney", repayAccountMoney);
		view.addObject("repayAccountNum", repayAccountNum);
		BaseLogUtils.info(logger, "confirmAndSubmitView", "跳转到确认提交页面.[batNos="+batNos+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	
	/**
	 * 
	 * @Title: confirmAndSubmitList   
	 * @Description: 确认提交
	 * @param: @param request
	 * @param: @param response
	 * @param: @return
	 * @param: @throws BaseException      
	 * @return: DataResultVO      
	 * @throws
	 */
	@RequestMapping(value = "/confirmAndSubmitList.do",  method = { RequestMethod.GET})
	@ResponseBody
	public Object confirmAndSubmitList(HttpServletRequest request, HttpServletResponse response ) throws BaseException {
		String batNos = request.getParameter("batNos");
		BaseLogUtils.info(logger, "confirmAndSubmitList", "核销款明细列表查询开始", CurrentThreadContext.getCurrentUserName()+"参数batNos:"+batNos);
		Pager page = new Pager();
		McrWriteOffConfirmSummaryQC qc = new McrWriteOffConfirmSummaryQC();
		List<String> li = Lists.newArrayList();
		li.add(batNos);
		qc.setBatNos(li);
		page.setCondition(qc);
		Pager pager = this.mcrWriteOffConfirmSummaryService.searchListPage(page);
		List<McrWriteOffConfirmSummaryVO> list = (List<McrWriteOffConfirmSummaryVO>) pager.getResultList();
		ListPageVO<McrWriteOffConfirmSummaryVO> listPage = new ListPageVO<McrWriteOffConfirmSummaryVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "confirmAndSubmitList", "核销款明细列表查询结束. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	
	@RequestMapping(value = "/confirmAndSubmit.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO confirmAndSubmit(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		long startTime = Clock.currentTimeMillis();
		BaseLogUtils.info(logger, "confirmAndSubmit", "核销款确认提交开始"+startTime, CurrentThreadContext.getCurrentUserName());
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			String repayAcc = request.getParameter("repayAcc");//我司还款账户
			String bankNo = request.getParameter("bankNo");//银行流水号
			String repayDate = request.getParameter("repayDate");//打款日期
			String repayMoney = request.getParameter("repayMoney");//打款金额
			String repayMoneyRemark = request.getParameter("repayMoneyRemark");//备注线下还款标识
			String repayInfo = request.getParameter("repayInfo");//核销款还款明细
			StringBuilder sb = new StringBuilder();
			List<McrWriteOffConfirmSummaryDVO> summaryListVO = Lists.newArrayList();
			if (StringUtils.isNotBlank(repayInfo)) {
				summaryListVO = JSON.parseArray(repayInfo, McrWriteOffConfirmSummaryDVO.class);
				for(McrWriteOffConfirmSummaryDVO vo:summaryListVO) {
					sb.append(vo.getBatNo()).append(",");
				}
			}
			String batNos = sb.toString().substring(0, sb.toString().length() - 1);
			
			PushWriteOffInfoDTO pushWriteOffInfoDTO = new PushWriteOffInfoDTO();
			pushWriteOffInfoDTO.setRepayAcc(repayAcc);
			pushWriteOffInfoDTO.setBankNo(bankNo);
			repayDate = DateUtils.formatDateToString(DateUtils.formatStringToDate(repayDate, DateUtils.YYYY_MM_DD) ,DateUtils.YYYYMMDD) ;
			pushWriteOffInfoDTO.setRepayDate(repayDate);
			DecimalFormat df = new DecimalFormat("######0.00");
			pushWriteOffInfoDTO.setRepayMoney(df.format(new BigDecimal(repayMoney) ));
			pushWriteOffInfoDTO.setRepayMoneyRemark(repayMoneyRemark);
			pushWriteOffInfoDTO.setBatNos(batNos);
			DataResultDTO dto = this.mcrWriteOffConfirmSummaryService.executePushWriteOffConfirmSummar(pushWriteOffInfoDTO);
			//调用中心推送接口
			if(null == dto  ||  BaseConstant.IS_YESNO_NO == dto.getSuccess() ) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(dto.getInfo());
				return result;
			}
		} catch (Exception e) {
			BaseLogUtils.info(logger, "confirmAndSubmit", "核销认款推送异常:"+e);
		}
		long endTime = Clock.currentTimeMillis();
		BaseLogUtils.info(logger, "confirmAndSubmit", "核销款确认提交结束"+endTime, CurrentThreadContext.getCurrentUserName());
		return result;
	}
}

